package com.weixing.mall.provider.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.ResultCodeEnum;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.orm.MPage;
import com.weixing.mall.base.utils.EnumUtil;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.core.annotation.NoRepeatSubmit;
import com.weixing.mall.core.annotation.SysLog;
import com.weixing.mall.base.enums.IsEnableEnum;
import com.weixing.mall.core.enums.OperateEnum;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.*;
import com.weixing.mall.core.utils.CommonUtil;
import com.weixing.mall.provider.api.model.enums.AgentLevelEnum;
import com.weixing.mall.provider.api.model.enums.AgentTypeEnum;
import com.weixing.mall.provider.api.model.enums.IsOfficialEnum;
import com.weixing.mall.provider.api.model.enums.TreeRoleEnum;
import com.weixing.mall.provider.api.model.query.AgentMemberQuery;
import com.weixing.mall.provider.api.model.vo.*;
import com.weixing.mall.provider.api.service.MemberServiceRpc;
import com.weixing.mall.provider.api.service.OrderServiceRpc;
import com.weixing.mall.provider.api.service.SysUserRpcService;
import com.weixing.mall.provider.model.domain.Agent;
import com.weixing.mall.provider.model.domain.AgentLog;
import com.weixing.mall.provider.model.domain.AgentPromote;
import com.weixing.mall.provider.model.dto.AgentBasicEditDto;
import com.weixing.mall.provider.model.dto.AgentBindDto;
import com.weixing.mall.provider.model.dto.AgentTransDto;
import com.weixing.mall.provider.model.enums.PromTypeEnum;
import com.weixing.mall.provider.model.enums.TransScopeEnum;
import com.weixing.mall.provider.model.excel.AgentED;
import com.weixing.mall.provider.model.query.AgentProfitQuery;
import com.weixing.mall.provider.model.query.AgentQuery;
import com.weixing.mall.provider.model.query.UpAgentQuery;
import com.weixing.mall.provider.model.vo.*;
import com.weixing.mall.provider.service.*;
import com.weixing.mall.provider.util.AgentUtil;
import com.weixing.mall.provider.util.EasyExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 代理商后台接口
 *
 * @author siashan
 * @since v1.0
 */
@Validated
@RestController
@RequestMapping("agent")
public class AgentController extends BaseController {

    @Autowired
    private IAgentService agentService;
    @Autowired
    private IAgentTranlsService agentTranlsService;
    @Autowired
    private MemberServiceRpc memberServiceRpc;
    @Autowired
    private SysUserRpcService sysUserRpcService;
    @Autowired
    private IAgentPromoteService agentPromoteService;
    @Autowired
    private OrderServiceRpc orderServiceRpc;
    @Autowired
    private IAgentLogService agentLogService;
    @Autowired
    private IAgentBonusGroupService agentBonusGroupService;
    @Autowired
    private IAgentInfoService infoService;


    /**
     * 保存代理商基本信息
     *
     * @param dto   参数
     * @return      代理id
     */
    @PostMapping("basic")
    @NoRepeatSubmit
    @SysLog(type = OperateEnum.S, desp = "编辑代理商基本信息")
    public Result<Long> basic(AgentBasicEditDto dto) {
        /*
         * 1、代理商基本信息维护操作，新增的时候可以选择代理等级，修改的时候不允许变更代理等级（这里随意变更会破坏整体代理树结构
         * ，造成代理收益计算混乱）
         * 2、代理商等级变更操作放在调整模块统一处理
         */
        if (null == dto.getId()) {
            String mobile = dto.getMobile();
            Agent byMobile = agentService.findByMobile(mobile);
            if (null != byMobile) {
                return ResultUtil.error("手机号已存在");
            }

            Agent byWechatNum = agentService.findByWechatNum(dto.getWechatNum());
            if (null != byWechatNum) {
                return ResultUtil.error("微信号已存在");
            }
        }
        Long id = agentService.saveBasic(dto);
        if (id.equals(0L)) {
            return ResultUtil.error(ResultCodeEnum.CODE_10015010);
        }
        return ResultUtil.success(id);
    }


    /**
     * 保存代理商基本信息--代理申请
     * @param dto    参数
     * @return       代理id
     */
    @PostMapping("basicApply")
    @NoRepeatSubmit
    @SysLog(type = OperateEnum.S, desp = "编辑会员申请代理商基本信息")
    public Result<Long> basicApply(AgentBasicEditDto dto) {
        /*
         * 1、代理商基本信息维护操作，新增的时候可以选择代理等级，修改的时候不允许变更代理等级（这里随意变更会破坏整体代理树结构
         * ，造成代理收益计算混乱）
         * 2、代理商等级变更操作放在调整模块统一处理
         */
        if (null == dto.getId()) {
            String mobile = dto.getMobile();
            Agent byMobile = agentService.findByMobile(mobile);
            if (null != byMobile) {
                return ResultUtil.error("手机号已存在");
            }
            Agent byWechatNum = agentService.findByWechatNum(dto.getWechatNum());
            if (null != byWechatNum) {
                return ResultUtil.error("微信号已存在");
            }
        }
        Long id = agentService.saveBasicApply(dto);
        if (id.equals(0L)) {
            return ResultUtil.error(ResultCodeEnum.CODE_10015010);
        }
        return ResultUtil.success(id);
    }

    /**
     * 代理商基本信息回显
     * @param id  代理id
     * @return    代理信息
     */
    @GetMapping("basic/{id}")
    public Result<AgentBasicEditVo> getBasicById(@PathVariable Long id) {
        AgentBasicEditVo agentEditVo = agentService.selectBasicEditVo(id);
        return ResultUtil.success(agentEditVo);
    }

    /**
     * 代理商基本信息回显
     *
     * @apiNote  不确定该接口是否有用
     *
     * @param id   代理id
     * @return     代理信息
     */
    @GetMapping("common/{id}")
    @NoNeedAccess
    public Result<AgentCommInfoVo> getCommInfo(@PathVariable Long id) {
        Agent agent = agentService.getById(id);
        if (ObjectUtil.isNotNull(agent)) {
            AgentInfoVo agentInfoVo = infoService.selectByAgentId(id);
            AgentCommInfoVo vo = new AgentCommInfoVo();
            vo.setAgentId(agent.getId());
            vo.setAgentSn(agent.getAgentSn());
            vo.setAgentWechat(agent.getWechatNum());
            vo.setAgencyFeeMonth(agent.getAgencyFeeMonth());
            vo.setAgencyFeeYear(agent.getAgencyFeeYear());
            vo.setAgentLevel(EnumUtil.getIEnum(AgentLevelEnum.class, agent.getAgentLevel()));
            vo.setAgentType(EnumUtil.getIEnum(AgentTypeEnum.class, agent.getAgentType()));
            vo.setIsOfficial(EnumUtil.getIEnum(IsOfficialEnum.class, agent.getIsOfficial()));
            vo.setAgentName(agent.getAgentName());
            vo.setIsEnable(EnumUtil.getIEnum(WhetherEnum.class, agent.getIsEnable()));
            vo.setIsBind(EnumUtil.getIEnum(WhetherEnum.class, agent.getIsBind()));
            vo.setFirstRenewTime(agent.getFirstRenewTime());
            vo.setLastMaturityTime(agent.getLastMaturityTime());
            vo.setMaturityTime(agent.getMaturityTime());
            vo.setEffectTime(agent.getEffectTime());
            vo.setMobile(agent.getMobile());
            vo.setAgentAddress(agentInfoVo.getProvince() + agentInfoVo.getCity() + agentInfoVo.getTown());
            if (ObjectUtil.isNotEmpty(agent.getParentId())) {
                if (!"0".equals(agent.getParentId())) {
                    Agent agentParent = agentService.getById(agent.getParentId());
                    if (ObjectUtil.isNotNull(agentParent)) {
                        vo.setAgentParent(agentParent.getAgentName());
                    }

                }
            }
            vo.setCustomerName(agent.getCustomerName());
            return ResultUtil.success(vo);

        }
        return null;
    }


    /**
     * 根据代理商编号查找代理
     * @param agentSn 代理优惠编码
     * @return        代理
     */
    @GetMapping("find/sn")
    public Result<AgentVo> getByAgentSn(@NotNull(message = "代理商编号不能为空") String agentSn) {
        AgentVo agentVo = agentService.selectByAgentSn(agentSn);
        return ResultUtil.success(agentVo);
    }

    /**
     * 代理商绑定
     *
     * @param agentBind 绑定参数
     * @return 绑定结果
     */
    @PostMapping("bind")
    @SysLog(type = OperateEnum.S, desp = "绑定代理商")
    public Result bind(AgentBindDto agentBind) {
        Agent agent = agentService.getById(agentBind.getId());
        Long parentId = agentBind.getParentId();

        if (WhetherEnum.YES.getValue().equals(agent.getIsBind())) {
            return ResultUtil.error("该代理已绑定代理结构树，不能重复绑定");
        }
        if (TreeRoleEnum.AGENT == agentBind.getParentRole()) {
            Agent parent = agentService.getById(parentId);
            if (null == parent) {
                return ResultUtil.error("父级代理商不存在");
            }
            if (null == agent) {
                return ResultUtil.error("代理不存在");
            }


            if (agent.getAgentLevel().intValue() <= parent.getAgentLevel().intValue()) {
                return ResultUtil.error("只能绑定比您等级高的代理商");
            }
            if (parent.getDiscount().doubleValue() >= agent.getDiscount().doubleValue()) {
                return ResultUtil.error("下级代理折扣不能低于上级代理");
            }
            agentService.agentBind(agent, parent);
        } else {
            Result<SysUserVo> voResult = sysUserRpcService.getById(parentId);
            if (!voResult.isSuccess()) {
                return ResultUtil.error("查询客服信息报错，请稍后重试");
            } else {
                SysUserVo kefu = voResult.getData();
                if (null == kefu) {
                    return ResultUtil.error("客服不存在");
                }
                agent.setIsBind(WhetherEnum.YES.getValue());
                agent.setCustomerId(kefu.getId());
                agent.setCustomerBindTime(new Date());
                agent.setCustomerName(kefu.getRealName());
                AgentUtil.updateAgentTree(agent);
                agentService.updateById(agent);


                AgentLog agentLog = agentLogService.findByAgentId(agent.getId());
                agentLog.setCustomerId(agent.getCustomerId());
                agentLog.setCustomerName(agent.getCustomerName());
                agentLogService.updateById(agentLog);

            }
        }

        return ResultUtil.success();
    }

    /**
     * 绑定代理商--会员申请
     *
     * @param agentId 代理商id
     * @return 绑定结果
     */
    @PostMapping("applyBind/{agentId}")
    @SysLog(type = OperateEnum.S, desp = "绑定代理商--会员申请")
    public Result applyBind(@PathVariable Long agentId) {
        Agent agent = agentService.getById(agentId);
        if (WhetherEnum.YES.getValue().equals(agent.getIsBind())) {
            return ResultUtil.error("该代理已绑定代理结构树，不能重复绑定");
        }
        if (null == agent.getInviteId()) {
            return ResultUtil.error("该代理不是会员申请的代理，不能走该绑定逻辑");
        }
        Agent invitor = agentService.getById(agent.getInviteId());
        if (null == invitor) {
            return ResultUtil.error("邀请人为空");
        } else {
            if (IsEnableEnum.DISABLE.getValue().equals(invitor.getIsEnable())) {
                return ResultUtil.error("邀请人已被禁用，不能绑定");
            }

            if (agent.getAgentLevel().intValue() <= invitor.getAgentLevel().intValue()) {
                return ResultUtil.error("只能绑定比您等级高的代理商");
            }
            if (invitor.getDiscount().doubleValue() >= agent.getDiscount().doubleValue()) {
                return ResultUtil.error("下级代理折扣不能低于上级代理");
            }
        }


        agentService.agentBind(agent, invitor);


        return ResultUtil.success();
    }


    /**
     * 启用/禁用代理商
     *
     * @param id       代理商id
     * @param isEnable 启用/禁用标识
     * @return 启用/禁用结果
     */
    @PostMapping("chgEnable/{id}/{isEnable}")
    @SysLog(type = OperateEnum.U, desp = "修改代理商状态")
    public Result agentChgEnable(@PathVariable Long id, @PathVariable IsEnableEnum isEnable) {
        Agent agent = agentService.getById(id);
        if (null == agent) {
            return ResultUtil.error("代理不存在");
        }
        agentService.changeEnable(id, isEnable);
        return ResultUtil.success();
    }


    /**
     * 代理商开户列表(管理后台使用)
     *
     * @param query 查询条件
     * @return 开户列表
     */
    @GetMapping("list")
    public Result<IPage<AgentVo>> list(AgentQuery query) {
        IPage<AgentVo> page = agentService.selectListOfPage(initMpPage(), query, false);
        return ResultUtil.success(page);
    }

    /**
     * 代理商开户列表Excel（管理后台使用）
     * @param query      查询条件
     * @param response   HttpServletResponse
     */
    @GetMapping("listExcel")
    public void listExcel( AgentQuery query, HttpServletResponse response) {
        IPage<AgentVo> page = agentService.selectListOfPage(initMpPage(), query, false);
        try {
            List<AgentED> target = Lists.newArrayList();
            page.getRecords().forEach(s -> {
                AgentED t = new AgentED();
                BeanUtils.copyProperties(s, t);
                target.add(t);
            });
            EasyExcelUtil.writeExcel(response, AgentED.class, target, "代理商开户列表");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "代理商开户列表--代理后台使用")
    @GetMapping("listForAgent")
    public Result<IPage<AgentVo>> listForAgent(AgentQuery query) {
        AgentAuth agentExt = AuthUtil.getAgentExt();
        if (null == query.getAgentId()) {
            query.setAgentId(agentExt.getAid());
        }
        IPage<AgentVo> page = agentService.selectListOfPageForAgent(initMpPage(), query, false);
        return ResultUtil.success(page);
    }


    /**
     * 代理商开户列表--结构树用
     *
     * @param query   查询条件
     * @return  结果
     */
    @GetMapping("listForTree")
    public Result<IPage<AgentVo>> listForTree(AgentQuery query) {
        query.setForTree(IsEnableEnum.ENABLE);
        IPage<AgentVo> page = agentService.selectListOfPageForAgent(initMpPage(), query, true);
        return ResultUtil.success(page);
    }

    /**
     * 代理商平移
     *
     * @param agentTransDto  参数
     * @return  结果
     */
    @PostMapping("transl")
    @SysLog(type = OperateEnum.S, desp = "代理商平移")
    public Result transl(AgentTransDto agentTransDto) {

        Agent agent = agentService.getById(agentTransDto.getId());
        if (null == agent) {
            return ResultUtil.error("代理商不存在");
        }
        // 判断是否有三角关系
        boolean hasGroup = agentBonusGroupService.hasGroup(agent.getId());

        // 判断是否有待审核订单
        if (checkHasAuditOrder(agent.getId())) {
            return ResultUtil.error("代理团队有未审核完成的订单，不能够平移");
        }
        if (TreeRoleEnum.AGENT == agentTransDto.getParentRole()) {
            int curLevel = agent.getAgentLevel().intValue();
            Agent parent = agentService.getById(agentTransDto.getParentId());
            if (hasGroup && agent.getCustomerId().equals(parent.getCustomerId())) {
                return ResultUtil.error("代理存在三角分红关系，不能平移");
            }
            if (null == parent) {
                return ResultUtil.error("父级代理商不存在");
            }
            if (parent.getAgentLevel().intValue() >= curLevel) {
                return ResultUtil.error("平移失败：平移后父级等级必须高于当前等级");
            }
            agentTranlsService.transl(agent, agentTransDto.getTransScope(), parent);
        } else {
            Result<SysUserVo> voResult = sysUserRpcService.getById(agentTransDto.getParentId());
            if (!voResult.isSuccess()) {
                return ResultUtil.error("查询客服信息报错，请稍后重试");
            } else {
                SysUserVo kefu = voResult.getData();
                if (null == kefu) {
                    return ResultUtil.error("客服不存在");
                }
                if (hasGroup && agent.getCustomerId().equals(kefu.getId())) {
                    return ResultUtil.error("代理存在三角分红关系，不能平移");
                }
                agentTranlsService.translToKefu(agent, agentTransDto.getTransScope(), kefu);
            }
        }

        return ResultUtil.success();
    }


    private boolean checkHasAuditOrder(long agentId) {
        Result result = orderServiceRpc.checkHasAuditOrder(agentId);
        if (!result.isSuccess()) {
            throw new BusinessException("查询代理是否有未审核订单失败");
        }
        Object data = result.getData();
        return WhetherEnum.YES.getValue().equals(data) ? true : false;
    }


    /**
     * 等级变动
     *
     * @param id        代理id
     * @param promType  变动类型
     * @param transScope 变动范围
     * @return  变动结果
     */
    @PostMapping("prom/{id}")
    @SysLog(type = OperateEnum.S, desp = "修改代理商等级")
    public Result agentPromotion(
            @PathVariable Long id,
            @NotNull(message = "变动类型不能为空") PromTypeEnum promType,
            @NotNull(message = "变动范围不能为空") TransScopeEnum transScope) {
        SysAuth auth =AuthUtil.getSysExt();
        Agent agent = agentService.getById(id);
        if (null == agent) {
            return ResultUtil.error("代理商不存在");
        }
        // 判断是否有待审核订单
        if (checkHasAuditOrder(agent.getId())) {
            return ResultUtil.error("代理团队有未审核完成的订单，不能够调整");
        }
        if (PromTypeEnum.UP == promType && AgentLevelEnum.DEALER.getValue().equals(agent.getAgentLevel())) {
            return ResultUtil.error("经销商不能够晋升");
        }
        if (PromTypeEnum.DOWN == promType && agent.getAgentLevel().intValue() >= AgentLevelEnum.LEVEL_3.getValue().intValue()) {
            return ResultUtil.error("当前等级不支持降级操作");
        }
        agentTranlsService.agentPromotion(agent, promType, transScope, auth.getUid());
        return ResultUtil.success();
    }


    /**
     * 代理商获利统计列表
     *
     * @param agentProfit  查询条件
     * @return   返回结果
     */
    @PostMapping("profit/statistic")
    public Result<Page<AgentProfitVo>> profitStatistic( AgentProfitQuery agentProfit) {
        // TODO 预估收益暂时不知道如何计算
//        agentProfit.setAgentId(auth.getAid());
        return ResultUtil.success(agentService.profitStatistic(initMpPage(), agentProfit));
    }


    /**
     * 代理商获利统计列表---代理商用
     * @param agentProfit
     * @return
     */
    @PostMapping("profit/statistic/agent")
    public Result<Page<AgentProfitVo>> profitStatisticForAgent(AgentProfitQuery agentProfit) {
        // TODO 预估收益暂时不知道如何计算
        return ResultUtil.success(agentService.profitStatistic(initMpPage(), agentProfit));
    }


    /**
     * 查询代理商会员信息
     *
     * @param auth
     * @param query
     * @return
     */
    @ApiOperation(value = "查询代理商会员信息")
    @GetMapping("member")
    public Result<IPage<AgentTableVo>> member(@SysInfo SysAuth auth, AgentMemberQuery query) {
        Long uid = auth.getUid();
        IPage<AgentTableVo> pageInfo = null;
        List<RoleVo> list = sysUserRpcService.getRoleById(uid).getData();
        for (RoleVo vo : list) {
            if (vo.getRoleCode().equals(GlobalConstant.RoleCode.ADMIN)) {
                pageInfo = agentService.selectOfPage(initMpPage(), query);
                return ResultUtil.success(pageInfo);
            }
        }
        for (RoleVo vo : list) {
            if (vo.getRoleCode().equals(GlobalConstant.RoleCode.KFADMIN)) {
                pageInfo = agentService.selectOfPage(initMpPage(), query);
                return ResultUtil.success(pageInfo);
            }
        }
        query.setCustomerId(uid);
        pageInfo = agentService.selectOfPage(initMpPage(), query);
        return ResultUtil.success(pageInfo);
    }

    /**
     * 查询代理商会员信息
     *
     * @param agentId       代理id
     * @param currentPage   当前页
     * @param pageSize      分页大小
     * @return              会员
     */
    @GetMapping("member/{agentId}")
    public Result<MPage<AgentMemberVo>> memberList(@PathVariable Long agentId, String currentPage, String pageSize) {
        Result<MPage<AgentMemberVo>> agentMemberVoResult = memberServiceRpc.selectByAgentId(agentId, currentPage, pageSize);
        System.out.println(JSON.toJSONString(agentMemberVoResult));
        return ResultUtil.success(agentMemberVoResult.getData());
    }


    /**
     * 已封单管理查询经销商下拉列表
     *
     * @apiNote 查询经销商信息(经销商名称或手机号（条件查出来的不一定唯一），不填查询条件就是查所有经销商)
     * @param upAgentQuery 查询条件
     * @return 查询结果
     */
    @PostMapping("selectByUpAgent")
    public Result<List<UpAgentVo>> selectByUpAgent(UpAgentQuery upAgentQuery) {
        return ResultUtil.success(agentService.selectByUpAgent(upAgentQuery));
    }


    /**
     * 根据代理姓名查询代理商
     *
     * @param agentName  代理姓名
     * @return  代理列表
     */
    @GetMapping("formAgent")
    public Result<List<UpAgentVo>> selectFormAgent(String agentName) {
        return ResultUtil.success(agentService.selectFormAgent(agentName));
    }


    /**
     * 代理结构树（客服主管用）
     *
     * @return 代理结构树
     */
    @GetMapping("treeTable")
    public Result<List<AgentTreeTableVo>> treeTable() {
        System.out.println(System.currentTimeMillis());
        Result<List<AgentTreeTableVo>> success = ResultUtil.success(agentService.tree(true));
        System.out.println(System.currentTimeMillis());
        return success;
    }

    /**
     * 代理结构树（客服）
     *
     * @apiNote 客服用
     * @return 代理结构树
     */
    @GetMapping("treeTable/kefu")
    public Result<List<AgentTreeTableVo>> treeTableOfKefu() {
        return ResultUtil.success(agentService.tree(false));
    }

    /**
     * 代理结构树（代理）
     *
     * @apiNote 代理用
     * @return 代理结构树
     */
    @GetMapping("treeTable/agent")
    public Result<List<AgentTreeTableVo>> treeTableOfAgent() {
        Long aid = AuthUtil.getAgentExt().getAid();
        return ResultUtil.success(agentService.treeForAgent(aid));
    }


    /**
     * 代理父级关系
     *
     * @param id 代理商id
     * @return 父级关系
     */
    @GetMapping("treeDetail/{id}")
    @NoNeedAccess
    public Result<Map<String, Object>> treeDetail(@PathVariable Long id) {
        Agent agent = agentService.getById(id);
        Map<String, Object> map = Maps.newHashMap();
        List<String> pInfos = Lists.newArrayList();
        if (AgentLevelEnum.DEALER.getValue().equals(agent.getAgentLevel())) {
            // 如果是经销商
            QueryWrapper<AgentPromote> wrapper = new QueryWrapper<AgentPromote>();
            wrapper.eq("agent_id", agent.getId());
            wrapper.ne("promote_type", PromTypeEnum.TRANSL.getValue());
            wrapper.orderByDesc("id");
            IPage<AgentPromote> page = agentPromoteService.page(initMpPage(), wrapper);
            List<AgentPromote> records = page.getRecords();
            if (CollUtil.isNotEmpty(records)) {

                AgentPromote agentPromote = records.get(0);
                Long parentBefore = agentPromote.getParentBefore();
                if (0 != parentBefore.longValue()) {
                    Agent pAgent = agentService.getById(parentBefore);
                    String pInfo = pAgent.getAgentName() + "(" + EnumUtil.getIEnum(AgentLevelEnum.class, pAgent.getAgentLevel()).getDesp() + ")";
                    pInfos.add(pInfo);
                }
            }

        } else {
            // 如果是代理
            getPinfos(pInfos, agent);
        }
        map.put("agentName", agent.getAgentName());
        map.put("kefu", agent.getCustomerName());
        map.put("pInfos", pInfos);
        return ResultUtil.success(map);
    }

    private void getPinfos(List<String> pInfos, Agent agent) {
        if (0 != agent.getParentId().longValue()) {
            Agent pAgent = agentService.getById(agent.getParentId());
            String pInfo = pAgent.getAgentName() + "(" + EnumUtil.getIEnum(AgentLevelEnum.class, pAgent.getAgentLevel()).getDesp() + ")";
            pInfos.add(pInfo);
            getPinfos(pInfos, pAgent);
        }
    }

    /**
     * 删除代理
     *
     * @param id 代理商id
     * @return 删除结果
     */
    @GetMapping("del/{id}")
    public Result del(@PathVariable Long id) {
        Agent agent = agentService.getById(id);
        if (null == agent) {
            return ResultUtil.error("代理不存在");
        }
        if (WhetherEnum.YES.getValue().equals(agent.getIsBind())) {
            return ResultUtil.error("已绑定结构树不能够删除");
        }
        agentService.delAgent(id);
        return ResultUtil.success("删除成功");
    }


    /**
     * 代理商重置密码
     *
     * @param id       代理商id
     * @param password 新密码
     * @return 重置结果
     */
    @PostMapping("resetPwd/{id}")
    public Result resetPwd(@PathVariable long id, String password) {
        Agent agent = agentService.getById(id);
        if (null == agent) {
            return ResultUtil.error("代理不存在");
        }
        agent.setPassword(CommonUtil.encryptPassword(password));
        agentService.resetPwd(agent, password);
        return ResultUtil.success();
    }


    /**
     * 代理商重置密码
     *
     * @param password 新密码
     * @return 重置结果
     * @
     */
    @PostMapping("resetPassword")
    public Result resetPwd(String password) {
        AgentAuth agentExt = AuthUtil.getAgentExt();
        Agent agent = agentService.getById(agentExt.getAid());
        if (null == agent) {
            return ResultUtil.error("代理不存在");
        }
        agent.setPassword(CommonUtil.encryptPassword(password));
        agentService.resetPwd(agent, password);
        return ResultUtil.success();
    }


    /**
     * 开户列表统计
     *
     * @return  统计
     */
    @GetMapping("listStatic")
    public Result listStatic() {
        // 使用总数
        int syTotal = agentService.countTotalByIsOfficial(IsOfficialEnum.PROBATION.getValue());
        // 正式总数
        int zsTotal = agentService.countTotalByIsOfficial(IsOfficialEnum.FORMAL.getValue());
        // 过期总数
        int expTotal = agentService.countExpTotal();
        // 禁用总数
        int jyTotal = agentService.countTotalByIsEnable(IsEnableEnum.DISABLE.getValue());
        Map<String, Integer> result = Maps.newHashMap();
        result.put("syTotal", syTotal);
        result.put("zsTotal", zsTotal);
        result.put("expTotal", expTotal);
        result.put("jyTotal", jyTotal);
        return ResultUtil.success(result);
    }
}
